package com.phenix.core.audit;

import com.phenix.core.security.PhenixUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.Optional;

/**
 * 审计功能
 *
 * @author zhenghui
 * @date 2020/4/29
 */
@Configuration
@Slf4j
public class UserAuditor implements AuditorAware<Long> {

    /**
     * 获取当前创建或修改的用户
     *
     * @return
     */
    @Override
    public Optional<Long> getCurrentAuditor() {
        PhenixUserDetails user;
        try {
            user = (PhenixUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (Objects.nonNull(user)) {
                return Optional.ofNullable(user.getUserId());
            }
            return Optional.of(0L);
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}